﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

/// <summary>
/// 个人结果界面
/// </summary>
public class ResultUIViewController : ViewController, IResultSceneUI
{
    public const float loadNextPanelTime = 4;
    [SerializeField]
    protected PersonalResultPanelData m_Data;

    protected ResultSceneUI m_PersonalResultPanel;

    bool m_AdMultied;

    public void Init(PersonalResultPanelData data)
    {
        m_Data = data;
    }

    static bool s_loadedInterstitial;
    protected override void WillLoadView()
    {
        base.WillLoadView();

        if (!s_loadedInterstitial || !Game.Instance.adManager.isInterstitialReady)
        {
            s_loadedInterstitial = true;

            if (Game.Instance)
            {
                Game.Instance.adManager.LoadInterstitialAd();
            }

            GameDebug.Log($"加载插屏广告");
        }
    }
    public override void OnLoadedViewEnd()
    {
        base.OnLoadedViewEnd();

        ShowUI();
    }

    void ShowUI()
    {
        if (m_PersonalResultPanel == null)
        {
            var pref = ResourceManager.Load<ResultSceneUI>(ViewPath.ResultPanel);
            m_PersonalResultPanel = Instantiate(pref, transform);
            m_PersonalResultPanel.uiListener = this;
            m_PersonalResultPanel.SetViewController(this);
        }

        m_PersonalResultPanel.Init(m_Data);

        if (Game.Instance && !Game.Instance.gameSetting.bgMusic)
        {
            if (m_Data.win)
            {
                //BattleSceneViewController.PlayMusic(ResourceManager.resultWinMusic);
                AudioController.instance.PlayBattleSound(Audio.sound_win, Vector3.zero, 1f);
            }
            else
            {
                //BattleSceneViewController.PlayMusic(ResourceManager.resultFailMusic);
                AudioController.instance.PlayBattleSound(Audio.sound_lose, Vector3.zero);
            }
        }
    }

    public static int s_count;
    public static int ShowAdCount = 2;

    bool m_InterstitialCallback;
    public void OnProcessAd(Action onEnd)
    {
        s_count++;
        if (s_count >= ShowAdCount)
        {
            s_count = 0;
            ShowAdCount = UnityEngine.Random.Range(1, 3);

            GameDebug.LogShowy("播放广告");

#if UNITY_EDITOR
            onEnd?.Invoke();
            return;
#endif

            Game.Instance.adManager.ShowInterstitialAd(onEnd, onEnd, (err) => { onEnd?.Invoke(); });
        }
        else
        {
            onEnd?.Invoke();
        }
    }

    public void OnProgressAnimEnd()
    {
        GameDebug.Log($"OnProgressAnimEnd  m_Data.level:{m_Data.level}");
    }

    public void OnClickGoBack()
    {
        Game.Instance.LoadCurLevelGame();
    }

    void GotoHomeScene()
    {
        //Game.Instance.rootNav.LoadDisplay<HomeSceneViewController>();
        
        LoadingSceneController.LoadScene("HomeScene");
    }
    
    /// <summary>
    /// 失败再挑战一次
    /// </summary>
    public void OnClickAgain()
    {
        if (!m_AdMultied)
        {
            if (Game.Instance != null && Game.Instance.adManager != null && Game.Instance.adManager.isInterstitialReady)
            {
                Game.Instance.adManager.ShowInterstitialAd(
                  () => Game.Instance.LoadGame(this.m_Data.level,  m_Data.mapId),
                  () => Game.Instance.LoadGame(this.m_Data.level,  m_Data.mapId),
                  (err) =>
                  {
                      Game.Instance.LoadGame(this.m_Data.level,  m_Data.mapId);
                  });
            }
            else
            {
                Game.Instance.LoadGame(this.m_Data.level,  m_Data.mapId);
            }
        }
        else
        {
            Game.Instance.LoadGame(this.m_Data.level, m_Data.mapId);
        }
    }



    /// <summary>
    /// 失败看广告跳过
    /// </summary>
    public virtual void OnClickSkip()
    {
        GameDebug.Log($"观看广告跳关");
#if UNITY_EDITOR
        OnSkip();
        return;
#endif
        AudioController.instance.PauseMusic();

        Game.Instance.adManager.PlayVideoAd(() =>
        {
            AudioController.instance.ResumeMusic();
            OnSkip();
        }
            , () =>
            {
                AudioController.instance.ResumeMusic();
            }, (err) =>
            {
                AudioController.instance.ResumeMusic();
                Game.Instance.ShowNoticePanel(err);
            });

    }

    void OnSkip()
    {
        Game.Instance.NextLevel();
        Game.Instance.LoadCurLevelGame();
    }

    public void OnClickAdMulti()
    {
        GameDebug.Log("播放广告");
#if UNITY_EDITOR
        OnAdMulti();
        return;
#endif
        AudioController.instance.PauseMusic();

        Game.Instance.adManager.PlayVideoAd(() =>
        {
            AudioController.instance.ResumeMusic();
            OnAdMulti();

            m_AdMultied = true;
        }
        , () =>
        {
            AudioController.instance.ResumeMusic();
        }, (err) =>
        {
            AudioController.instance.ResumeMusic();
            Game.Instance.ShowNoticePanel(err);
        });
    }

    /// <summary>
    /// 胜利继续
    /// </summary>
    public void OnClickNext()
    {
        if (MGame.instance.review)
        {
            LoadingSceneController.LoadScene("ReviewScene");
            return;
        }
        
        if (!Game.Instance)
        {
            LoadingSceneController.LoadScene($"Game");
            return;
        }
        
        if (!m_AdMultied)
        {
            OnProcessAd(() =>
            {
                Game.Instance.NextLevel();
                Game.Instance.LoadCurLevelGame();
            });
        }
        else
        {
            Game.Instance.NextLevel();
            Game.Instance.LoadCurLevelGame();
        }
    }

    public void OnAdMulti()
    {
        OnAdMulti(5);
        /*        var resultScene = GetComponentInParent<ResultSceneDisplayController>();
                resultScene.OnAdMulti(multi);*/
    }
    public void OnAdMulti(int multi)
    {
        int coinAdd = (int)(m_Data.coin * (multi - 1));

        if (Game.Instance)
        {
            Game.Instance.user.UpdateCoin(Game.Instance.user.coin + coinAdd);
        }

        if (this.m_PersonalResultPanel)
        {
            this.m_PersonalResultPanel.HideAdMultiBtn();

            this.m_PersonalResultPanel.SetAddScore(m_Data.coin * multi);
            
            Debug.LogError($"hide multibtn");
        }

        m_Data.coin = (int)(multi * m_Data.coin);
        Debug.Log($"ad multi:{multi}  coin:{m_Data.coin}");
        /*        var resultScene = GetComponentInParent<ResultSceneDisplayController>();
                resultScene.OnAdMulti(multi);*/

#if GameAnalytics
        GameAnalyticsSDK.GameAnalytics.NewDesignEvent("AdMulti");
#endif
    }


    public override void WillHideView()
    {
        base.WillHideView();
    }

    public override void OnViewDelete()
    {
        base.OnViewDelete();

        if (m_PersonalResultPanel)
        {
            m_PersonalResultPanel.Release();
            Destroy(m_PersonalResultPanel.gameObject);
        }
    }

    private void OnDestroy()
    {
        m_Data = null;
    }


}